package com.caird.pmp.iot.server;

import com.caird.common.utils.DataTypeUtils;
import com.caird.pmp.iot.handler.HandlerFactory;
import com.caird.pmp.iot.handler.IHandler;
import com.caird.pmp.iot.message.MessageBase;
import com.caird.pmp.iot.message.MessageFactory;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import java.util.concurrent.ExecutorService;

@ChannelHandler.Sharable
@Slf4j
@Component
public class BbHandler extends SimpleChannelInboundHandler<ByteBuf> {

    @Autowired
    private ExecutorService workers;

    @Autowired
    private BbChannelManager bbChannelManager;

    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        log.info("设备连接：" + ctx.channel().remoteAddress().toString());
    }

    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
        log.info("设备断开：" + ctx.channel().remoteAddress().toString());
    }

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, ByteBuf byteBuf) throws Exception {

        int id = byteBuf.getShort(1);

        if (0x0002 != id && 0x0100 != id && 0x0102 != id && 0x01E0 != id) {
            if (!bbChannelManager.isLogin(ctx.channel())) {
                ctx.close();
                log.info("设备非法断开：" + ctx.channel().remoteAddress().toString());
                return ;
            }
        }

        MessageBase deviceMessage = (MessageBase) MessageFactory.make((short) id);
        if (null == deviceMessage) {
            log.warn("消息ID不支持：" + DataTypeUtils.byteBuf2HexString(byteBuf.resetReaderIndex()));
            return;
        }


        if (!deviceMessage.decode(byteBuf)) {
            log.warn("消息解码失败：" + DataTypeUtils.byteBuf2HexString(byteBuf.resetReaderIndex()));
            return;
        }

        //消息处理
        IHandler handler = HandlerFactory.get((short)id);
        if (null == handler) {
            log.warn("消息无法处理：" + DataTypeUtils.byteBuf2HexString(byteBuf.resetReaderIndex()));
            return;
        }

        //数据接收日志
        log.info("接收：" + DataTypeUtils.byteBuf2HexString(byteBuf.resetReaderIndex()));

        workers.execute(() -> {
            try {
                handler.handle(ctx.channel(), deviceMessage);
            } catch (Exception e) {
                e.printStackTrace();
            }
        });
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        ctx.close();
        log.info("设备异常断开：" + ctx.channel().remoteAddress().toString());
        cause.printStackTrace();
    }

    @Override
    public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
        ctx.close();
        log.info("设备超时断开：" + ctx.channel().remoteAddress().toString());
    }

}
